﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Toolbox
{
    public partial class frmTool : Form
    {
        private ToolboxDataContext dbToolbox = new ToolboxDataContext();
        private bool lHasChanged = false;
        public static int nToolID;

        public frmTool(int nID)
        {
            InitializeComponent();
            nToolID = nID;

            var dsA = from A in dbToolbox.Authors orderby A.Author1 select A;
            authorBindingSource.DataSource = dsA;

            var dsTool = from T in dbToolbox.Tools where T.ToolID == nID select T;
            toolBindingSource.DataSource = dsTool;
        }        

        public void SaveThisTool()
        { 
           SaveChanges();
        }

        public void FindText(string strSearch)
        {
            int nStart = 0;
            
            switch (tabTool.SelectedIndex)
            {               
                case 0:
                    richTextDescription.Focus();
                    nStart = richTextDescription.SelectionStart;                    
                    richTextDescription.Find(strSearch,nStart+1,RichTextBoxFinds.None);
                    break;
                case 1:
                    rtbScript.Focus();                    
                    nStart = rtbScript.SelectionStart;                    
                    rtbScript.Find(strSearch, nStart+1, RichTextBoxFinds.None);
                    break;
                case 2:
                    uRLNoteTextBox.Focus();
                    nStart = uRLNoteTextBox.SelectionStart;
                    uRLNoteTextBox.SelectionStart = uRLNoteTextBox.Text.IndexOf(strSearch, nStart+1);
                    uRLNoteTextBox.SelectionLength = 0;
                    break;
                case 3:
                    break;
                case 4:
                    noteTextBox.Focus();
                    nStart = noteTextBox.SelectionStart;
                    noteTextBox.SelectionStart = noteTextBox.Text.IndexOf(strSearch, nStart+1);
                    noteTextBox.SelectionLength = 0;
                    break;
                default:
                    break;
            }                
        }

        public void ReplaceText(string strSearch, string strReplace)
        {
            int nStart = 0;

            switch (tabTool.SelectedIndex)
            {
                case 0:
                    richTextDescription.Focus();
                    nStart = richTextDescription.SelectionStart;
                    if (richTextDescription.Find(strSearch, nStart + 1, RichTextBoxFinds.None) > 0)
                    {
                        Clipboard.SetText(strReplace);
                        richTextDescription.Paste();
                    }                    
                    break;
                case 1:
                    rtbScript.Focus();
                    nStart = rtbScript.SelectionStart;
                    if (rtbScript.Find(strSearch, nStart + 1, RichTextBoxFinds.None) > 0)
                    {
                        Clipboard.SetText(strReplace);
                        rtbScript.Paste();
                    }
                    break;
                case 2:
                    uRLNoteTextBox.Focus();
                    nStart = uRLNoteTextBox.SelectionStart;
                    uRLNoteTextBox.SelectionStart = uRLNoteTextBox.Text.IndexOf(strSearch, nStart + 1);
                    uRLNoteTextBox.SelectionLength = 0;
                    break;
                case 3:
                    break;
                case 4:
                    noteTextBox.Focus();
                    nStart = noteTextBox.SelectionStart;
                    noteTextBox.SelectionStart = noteTextBox.Text.IndexOf(strSearch, nStart + 1);
                    noteTextBox.SelectionLength = 0;
                    break;
                default:
                    break;
            }
        }

        private void frmTool_Load(object sender, EventArgs e)
        {
            BindFileList();
            BindTags();
            this.Text = titleTextBox.Text;
            lHasChanged = false;

            this.Show();

            this.FormBorderStyle = FormBorderStyle.None;
            this.ControlBox = false;
            this.MinimizeBox = false;
            this.MaximizeBox = false;
            this.Dock = DockStyle.Fill;
            tabTool.Dock = DockStyle.Fill;

            tabTool.SelectedIndex = 1;
            tabTool.SelectedIndex = 0;

            if ((from S in dbToolbox.ToolScripts where S.ToolID == nToolID select S.ToolID).Count<int>() > 0)
            {
                lbScripts.BackColor = Color.LimeGreen;
            }

            if ((from S in dbToolbox.ToolNotes where S.ToolID == nToolID select S.ToolID).Count<int>() > 0)
            {
                lbNotes.BackColor = Color.LimeGreen;
            }

            if ((from S in dbToolbox.ToolURLs where S.ToolID == nToolID select S.ToolID).Count<int>() > 0)
            {
                lbLinks.BackColor = Color.LimeGreen;
            }

            if (dbToolbox.FileCountByToolID(nToolID) > 0)
            {
                lbFiles.BackColor = Color.LimeGreen;
            }

        }

        private void uRLNoteTextBox_TextChanged(object sender, EventArgs e)
        {
            lblURLNote.Visible = (uRLNoteTextBox.Text.Length == 0);
        }

        private void noteTextBox_TextChanged(object sender, EventArgs e)
        {
            lblNote.Visible = (noteTextBox.Text.Length == 0);
        }

        private void lstFiles_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            string strPath = Properties.Settings.Default.FileStreamShare;
            strPath += @"\" + nToolID.ToString();
            System.Diagnostics.Process.Start("explorer.exe", strPath);
        }

        private void lstFiles_DragDrop(object sender, DragEventArgs e)
        {
            string[] filenames = e.Data.GetData(DataFormats.FileDrop) as string[];
            foreach (string file in filenames)
            {
                string strPath = Properties.Settings.Default.FileStreamShare;
                strPath += @"\" + nToolID.ToString() +@"\";

                if (System.IO.Directory.Exists(strPath))
                {
                    System.IO.File.Copy(file, strPath + System.IO.Path.GetFileName(file), true);
                }
                else
                {
                    System.IO.Directory.CreateDirectory(strPath);
                    System.IO.File.Copy(file, strPath + System.IO.Path.GetFileName(file), true);
                }

                int nCount = 1;

                while (nCount < 5 & !System.IO.File.Exists(strPath + System.IO.Path.GetFileName(file)))
                {
                    System.Threading.Thread.Sleep(1000);
                    nCount += 1;
                }

                //dbToolbox.CreateFileStreamMap(int.Parse(toolIDTextBox.Text), System.IO.Path.GetFileNameWithoutExtension(file));
            }

            BindFileList();
        }

        private void lstFiles_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
        }

        private void SaveChanges()
        {
            scriptTextBox.ReadOnly = false;
            scriptTextBox.Focus();
            scriptRtfTextBox.Text = rtbScript.Rtf;
            scriptTextBox.Text = rtbScript.Text;
            scriptTextBox.ReadOnly = true;
            rtbScript.Focus();

            this.Validate();

            toolScriptsBindingSource.EndEdit();
            toolURLsBindingSource.EndEdit();
            toolNotesBindingSource.EndEdit();
            toolBindingSource.EndEdit();

            try
            {
                dbToolbox.SubmitChanges(System.Data.Linq.ConflictMode.ContinueOnConflict);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show("An error was encountered while saving.  Please try again.  If problem persists notify developer.");
            }

            lHasChanged = false;
        }

        private void colorizeScript()
        {
            string strTestText = rtbScript.Text;
            string strTestRtb = rtbScript.Rtf;

            Manoli.Utils.CSharpFormat.TsqlFormat clrz = new Manoli.Utils.CSharpFormat.TsqlFormat();
            rtbScript.Rtf = clrz.FormatString(rtbScript.Text);

            if (strTestText != rtbScript.Text)
            {
                /* Make sure the colorize script didn't screw things up - if so, undo */
                rtbScript.Rtf = strTestRtb;
            }
        }

        private void scriptTextBox_TextChanged(object sender, EventArgs e)
        {
            rtbScript.Rtf = scriptRtfTextBox.Text;
        }

        private void dgvURL_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (dgvURL[e.ColumnIndex, e.RowIndex].Value.ToString().Length > 0)
                {
                    System.Diagnostics.Process.Start("iexplore.exe", dgvURL[e.ColumnIndex, e.RowIndex].Value.ToString());
                }
            }
            catch
            {
                // that's ok
            }
        }

        private void btnAddScript_Click(object sender, EventArgs e)
        {
            toolScriptsBindingSource.AddNew();
        }

        private void BindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            lHasChanged = true;   
        }

        private void descriptionRichTextBox_TextChanged(object sender, EventArgs e)
        {
            if (!richTextDescription.Focused) richTextDescription.Rtf = descriptionRichTextBox.Text;
        }

        private void richTextDescription_TextChanged(object sender, EventArgs e)
        {
            if (richTextDescription.Focused)
            {
                descriptionRichTextBox.Text = richTextDescription.Rtf;
                descriptionTextBox.Text = richTextDescription.Text;
            }
        }


        private void toolScriptsDataGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (MessageBox.Show("Are you sure you want to remove this script?", "Alert", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    e.Handled = true;
                }
            }
        }

        private void BindFileList()
        {
            lstFiles.Clear();
            using (SqlConnection cn = new SqlConnection(dbToolbox.Connection.ConnectionString))
            {
                using (SqlCommand cm = new SqlCommand("select stream_id, name, file_type from toolfile where stream_id in (select stream_id from toolfilemap where toolid=@toolid)", cn))
                {
                    cm.Parameters.AddWithValue("@toolid", nToolID);
                    cn.Open();
                    using (SqlDataReader rdr = cm.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            lstFiles.Items.Add(rdr[0].ToString(), rdr[1].ToString(), GetFileType(rdr[2].ToString()));
                        }
                    }
                }
            }
        }
        
        private int GetFileType(string filetype)
        {
            if ("-- .doc .rtf .docx".Contains(filetype.ToLower())) return 0;
            if ("-- .xml .xls .xlsx .csv .tab".Contains(filetype.ToLower())) return 1;
            if ("-- .pdf".Contains(filetype.ToLower())) return 2;
            if ("-- .png .gif .jpg .bmp .tif .jpeg .tiff".Contains(filetype.ToLower())) return 3;
            return 4;            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(rtbScript.Rtf.ToString());

            Microsoft.SqlServer.Management.SqlParser.Parser.ParseResult objResult;            
            objResult = Microsoft.SqlServer.Management.SqlParser.Parser.Parser.Parse(rtbScript.Text);

            if (objResult.Errors.Count() > 0)
            {
                foreach (var item in objResult.Errors)
                {
                    MessageBox.Show(item.Message.ToString() + System.Environment.NewLine + System.Environment.NewLine + "Line Number: " + item.Start.LineNumber);
                }
            }
            else
            {
                MessageBox.Show("No Errors Found.");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            colorizeScript();
        }

        private void frmTool_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (lHasChanged)
            {
                if (MessageBox.Show("Would you like to save changes?", "Alert", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    SaveChanges();
                }
            }
        }

        private void btnDelScript_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to remove this script?","Alert",MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                toolScriptsBindingSource.RemoveCurrent();
            }
        }

        private void rtbScript_Leave(object sender, EventArgs e)
        {
            scriptTextBox.ReadOnly = false;
            scriptTextBox.Focus();
            scriptRtfTextBox.Text = rtbScript.Rtf;
            scriptTextBox.Text = rtbScript.Text;
            scriptTextBox.ReadOnly = true;
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(rtbScript.Text);
        }

        private void btnCloseForm_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmTool_VisibleChanged(object sender, EventArgs e)
        {
            this.Refresh();
        }

        private void linkTag_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            dlgTags dlgT = new dlgTags(nToolID);
            dlgT.ShowDialog();
            BindTags();
        }

        private void BindTags()
        {
            lstTags.Items.Clear();

            using (SqlConnection cn = new SqlConnection(dbToolbox.Connection.ConnectionString))
            {
                cn.Open();
                using (SqlCommand cm = new SqlCommand("select tag from tooltag where toolid=@toolid order by tag", cn))
                {
                    cm.Parameters.AddWithValue("@toolid", nToolID);
                    using (SqlDataReader rdr = cm.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            lstTags.Items.Add(rdr[0].ToString());
                        }
                    }
                }
            }
        }

        private void toolScriptsDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            // don't care
        }

        private void pnlDrag_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
        }

        private void pnlDrag_DragDrop(object sender, DragEventArgs e)
        {
            string[] filenames = e.Data.GetData(DataFormats.FileDrop) as string[];
            foreach (string file in filenames)
            {
                System.IO.StreamReader myFile = new System.IO.StreamReader(file);
                string myString = myFile.ReadToEnd();
                myFile.Close();

                if (rtbScript.Text.Length > 0)
                {
                    if (MessageBox.Show("Overwrite existing script with this file?","Alert",MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        return;  
                    }
                }

                rtbScript.Text = myString;
                colorizeScript();

                return;                
            }
        }

    }
}
